package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component //组件扫描，为当前类创建实例化对象，执行任务
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    //定时超过十五分钟未支付的订单，取消订单处理
//    @Scheduled(cron="0 0/1 * * * ?")
    @Scheduled(cron="0/30 * * * * ?")
    public  void processTimeoutOrder(){
        log.info(">>>>>>>>>>>>>>>> OrderTask processTimeOutOrder is runnning<<<<<<<<<<<<<<<");
        //1.查询，超过15分钟 未支付的订单
        //查询超过15分钟，当前时间-15Min=时间 和创建订单时间比较
        LocalDateTime orderTime =LocalDateTime.now().minusMinutes(15);
        List<Orders> orderList=orderMapper.getByStatusAndOrdertimeLT(Orders.PAID,orderTime);
        //2.遍历订单集合，修改订单的状态位6(已取消)
        for (Orders orders :orderList){
            orders.setStauts(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("订单超时未支付");
            orderMapper.update(orders);

            //恢复库存
        }
        log.info(">>>>>>>>>>>>>>>> OrderTask processTimeOutOrder is success<<<<<<<<<<<<<<<");
    }
    //商家点击完成订单操作
//    @Scheduled(cron="0 0 1 * * ?")
    @Scheduled(cron="0/30 * * * * ?")
    public  void processDeliveryOrder(){
        log.info(">>>>>>>>>>>>>>>> OrderTask processTimeOutOrder is runnning<<<<<<<<<<<<<<<");
        //1.查询，超过15分钟 未支付的订单
        //查询超过15分钟，当前时间-15Min=时间 和创建订单时间比较
        LocalDateTime orderTime =LocalDateTime.now().minusHours(1);
        List<Orders> orderList=orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS,orderTime);
        //2.遍历订单集合，修改订单的状态位6(已取消)
        for (Orders orders :orderList){
            orders.setStauts(Orders.COMPLETED);
            orderMapper.update(orders);

            //恢复库存
        }
        log.info(">>>>>>>>>>>>>>>> OrderTask processTimeOutOrder is success<<<<<<<<<<<<<<<");
    }
}
